#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>


#define MAX 10000
#define NUMTH 15

void *bubble();

pthread_mutex_t *mutex;
int *vet;

void *bubble(void *t){
	int trocou;
	int i = 0;
	int temp;
	int vetSize = (int)t;
			printf("******************%d**************************\n", vetSize);
	do{
		trocou = 0;
			printf("******************%d**************************\n", vetSize);

		for(i=0; i < (vetSize -1); i++){
			pthread_mutex_lock(&mutex[i]);
			pthread_mutex_lock(&mutex[i+1]);
			if(vet[i+1]<vet[i]){
				temp = vet[i];
				vet[i] = vet[i+1];
				vet[i+1] = temp;
				trocou = 1;
			}
			pthread_mutex_unlock(&mutex[i]);
			pthread_mutex_unlock(&mutex[i+1]);
			
		}

	}while(trocou);
  pthread_exit(NULL);
}



int main(int argc, char *argv[])
{		int i;
		int numThreads = atoi(argv[1]); /*Numero de Threads a serem criadas*/
		int sizeVector = atoi(argv[2]); /*Tamanho do vetor dados passado*/
	
		pthread_t *threads;	
		vet = malloc(sizeVector*sizeof(int));
		mutex = malloc(sizeVector*sizeof(pthread_mutex_t));

		threads = malloc(numThreads*sizeof(pthread_t));
  		pthread_attr_t attr;
  		pthread_attr_init(&attr);
  		pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
		for(i=0; i < numThreads ; i++){
			pthread_mutex_init(&mutex[i], NULL);	
  		}

		for(i=0; i< sizeVector; i++){
			vet[i] = random()%100;
			printf("%d*", vet[i]);
		}

	
		for(i=0 ; i< numThreads; i++){
			printf("*********************************************\n");
			printf("Criando THREAD = %d\n", i);
			printf("*********************************************\n");
			pthread_create(&threads[i], &attr, bubble, (void *)sizeVector);
		}

		 /* Wait for all threads to complete */
 		for (i = 0; i < numThreads; i++) {

    			pthread_join(threads[i], NULL);
  		}
		printf("*********************************************\n");
		printf("*********************************************\n");
		printf("*********************************************\n");
		for(i=0; i< sizeVector; i++){
			printf("%d.", vet[i]);
		}
			printf("\n");
  		
		/* Clean up and exit */
		pthread_attr_destroy(&attr);
  		for (i = 0; i < numThreads; i++) pthread_mutex_destroy(&mutex[i]);
  	
  		pthread_exit (NULL);
}
